import 'package:flutter_fitness/model/entity/record.dart';
import 'package:sqflite/sqflite.dart';

import 'DBHelper.dart';

class RecordProvider {
  Database db;

  Future open() async {
    db = await DBHelper.instance.open();
  }

  Future<Record> insert(Record record) async {
    record.id = await db.insert(tableRecord, record.toMap());
    return record;
  }

  Future<Record> getRecordByUserIdAndTime(
      int userId, int year, int month, int day) async {
    List<Map> maps = await db.query(tableRecord,
        where:
            '$columnUserId = ? AND $columnYear = ? AND $columnMonth = ? AND $columnDay = ?',
        whereArgs: [userId, year, month, day]);
    if (maps.length > 0) {
      return Record.fromMap(maps.first);
    }
    return null;
  }

  Future<Record> getRecord(int id) async {
    List<Map> maps =
        await db.query(tableRecord, where: '$columnId = ?', whereArgs: [id]);
    if (maps.length > 0) {
      return Record.fromMap(maps.first);
    }
    return null;
  }

  Future<int> getUserRecordCount(int userId) async {
    List<Map> maps = await db
        .query(tableRecord, where: '$columnUserId = ?', whereArgs: [userId]);
    return maps == null ? 0 : maps.length;
  }

  Future<int> update(Record record) async {
    return await db.update(tableRecord, record.toMap(),
        where: '$columnId = ?', whereArgs: [record.id]);
  }

  Future close() async => db.close();
}
